package com.itany.corejava.code11_线程.zuoye;

/**
 * @author MissChen
 * @date 2024年03月12日 16:58
 * 定义2个线程类extends Thread，一个线程类输出A，一个线程类输出B，交替输出10次
 */
public class Test02 {
    public static boolean flag=true;
    public static void main(String[] args) {
        Object o=new Object();
        A a=new A(o);
        B b=new B(o);
        a.start();
        b.start();

    }
}
class A extends Thread{
    private Object o;
    private int num=1;

    public A(Object o) {
        this.o = o;
    }

    @Override
    public void run() {
        while(true){
            synchronized (o){
                if(num==11){
                    break;
                }else{
                    if(Test02.flag){
                        System.out.println("A"+num);
                        Test02.flag=false;
                        num++;
                    }
                }
            }
        }
    }
}
class B extends Thread{
    private Object o;
    private int num=1;

    public B(Object o) {
        this.o = o;
    }

    @Override
    public void run() {
        while(true){
            synchronized (o){
                if(num==11){
                    break;
                }else{
                    if(!Test02.flag){
                        System.out.println("B"+num);
                        Test02.flag=true;
                        num++;
                    }
                }
            }
        }
    }
}